package com.factory.common.model;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PageQuery {
    int page = 0;
    int limit = 0;
    Map<String, Object> data;
    String order = "";

    public PageQuery(Map<String, Object> queryMap, Class dataClass) {
        ObjectMapper mapper = new ObjectMapper();
        if (queryMap.containsKey("page")) {
            this.page = Integer.parseInt(queryMap.get("page").toString());
        }
        if (queryMap.containsKey("limit")) {
            this.limit = Integer.parseInt(queryMap.get("limit").toString());
        }
        if (queryMap.containsKey("data")) {
            this.data = new HashMap<String, Object>();
            Set<Map.Entry<String, Object>> sets = ((Map<String, Object>) queryMap.get("data")).entrySet();
            try {
                if (dataClass != null) {
                    for (Map.Entry<String, Object> set : sets) {
                        if (StringUtils.isNotBlank(set.getValue().toString())) {
                            Field f = dataClass.getDeclaredField(set.getKey());
                            String value = set.getValue().toString();
                            if ("String".equals(f.getType().getSimpleName())) {
                                value = "%" + value + "%";
                            }
                            this.data.put(set.getKey(), value);
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if (queryMap.containsKey("order")) {
            this.order = queryMap.get("order").toString();
        }
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }
}
